import React, { useEffect, useRef, useState } from 'react';
import { message } from 'antd';
import classNames from 'classnames';
import styles from './index.less';
import { InnerUpload } from '@/pages/pc/components/Upload';
import { formatSizeUnits, uid } from '@/utils';
import { allGet, allPost } from '@/services/pc';
import DiskModal from './diskModal';

const MaterialUpload = ({
  className = '',
  style = {},
  size = 20,
  value: propsValue = {} as any,
  payload = {},
  action,
  name = 'file',
  onChange = (value) => null as any,
  controlled = false,
  onSuccess = (value) => true as any,
  diskPayload = {},
}) => {
  const [value, setValue] = useState<any>(propsValue);
  const init = async () => {};
  const UploadRef = useRef<any>();

  const [diskShow, setDiskShow] = useState(false);
  const [diskInitialValues, setDiskInitialValues] = useState({});

  useEffect(() => {
    init();
  }, []);

  useEffect(() => {
    if (controlled && JSON.stringify(propsValue) !== JSON.stringify(value)) {
      console.log(propsValue, 'propsValue');
      setValue(propsValue);
    }
  }, [propsValue]);

  const beforeUpload = async (file) => {
    // 尺寸不符合
    const isSizeOK = file.size < 1024 * 1024 * size;
    if (!isSizeOK) {
      message.error(`文件大小不能超过 ${size} Mb`);
      return false;
    }

    file.key = file?.uid || uid();

    return file;
  };
  const handleUploadChange = async (fileList) => {
    const newValue = {
      ...value,
      attach: fileList,
    };
    setValue(newValue);
    onChange?.(newValue);
  };
  const handleSuccess = async (fileList) => {
    const newValue = {
      ...value,
      attach: fileList,
    };
    onSuccess?.(newValue);
  };

  const upLoadProps = {
    fileList: value.attach || [],
    onChange: handleUploadChange,
    name,
    action,
    multiple: true,
    data: () => payload,
    beforeUpload: beforeUpload,
    onSuccess: handleSuccess,
  };

  const handleDeleteAttach = async (index, file) => {
    if (file.status === 'done') {
      await allGet({
        params: { mod: 'attachment', do: 'delete', aid: file.aid, version: 'pc1.0' },
      });
    }
    UploadRef.current?.removeFile?.(file);
  };
  const handleDeleteDisk = async (index, file) => {
    const response = await allGet({
      params: { mod: 'attachment', do: 'delete', aid: file.aid, version: 'pc1.0' },
    });
    if (!response.success) return;
    const disk = value.disk || [];
    const newDisk = [...disk];
    newDisk.splice(index, 1);
    const newValue = {
      ...value,
      disk: newDisk,
    };
    setValue(newValue);
    onSuccess?.(newValue);
  };

  const handleDiskSave = async (values) => {
    console.log(values, 222);
    if (values.aid) {
      const response = await allPost({
        data: {
          mod: 'attachment',
          do: 'disk',
          version: 'pc1.0',
          aid: values.aid,
          url: values.url,
          name: values.name,
        },
      });
      if (response.success) {
        const disk = [...(value.disk || [])];
        const index = disk.findIndex((item) => item.aid === values.aid);
        if (index >= 0) {
          disk[index] = {
            ...disk[index],
            attachment: values.url,
            url: values.url,
            name: values.name,
          };
          setValue({
            ...value,
            disk,
          });
        }
        setDiskInitialValues({});
        setDiskShow(false);
      }
    } else {
      const response = await allGet({
        params: {
          mod: 'swfupload',
          ac: 'course',
          field: 'disk',
          version: 'pc1.0',
          ...diskPayload,
          ...values,
        },
      });
      if (response.success) {
        setValue({
          ...value,
          disk: [
            { aid: response.data.attachid, name: values.name, url: values.url },
            ...value.disk,
          ],
        });
        setDiskInitialValues({});
        setDiskShow(false);
      }
    }
  };

  const handleEditDisk = (item) => {
    setDiskInitialValues(item);
    setDiskShow(true);
  };

  const handleAddDisk = () => {
    setDiskShow(true);
  };

  const isEmpty = !!!(value.attach?.length > 0 || value.disk?.length > 0);
  return (
    <div
      className={classNames(styles.materialupload, className, `cgjoy-material-upload`)}
      style={style}
    >
      <div className={styles.header}>
        <div className={styles.left}>
          <div className={styles.line} />
          <div className={styles.text}>课程素材</div>
          <div className={styles.subtext}>Course materials</div>
        </div>
        <div className={styles.right}>
          <InnerUpload ref={UploadRef} {...(upLoadProps as any)} className={styles.upload}>
            <div className={classNames('material-upload-button', styles.button)}>
              上传 [本地素材]
            </div>
          </InnerUpload>
          <div
            className={classNames('material-upload-button', styles.button)}
            onClick={handleAddDisk}
          >
            添加 [网盘地址]
          </div>
        </div>
      </div>
      <div className={styles.body}>
        {isEmpty ? (
          <div className={styles.empty}>
            <i className={styles.icon} />
            <div className={styles.text}>未添加素材</div>
          </div>
        ) : (
          <div className={styles.table}>
            <div className={styles.tableheader}>
              <div className={classNames(styles.td, styles.name)}>文件</div>
              <div className={classNames(styles.td, styles.type)}>类型</div>
              <div className={classNames(styles.td, styles.size)}>大小</div>
              <div className={classNames(styles.td, styles.action)}>操作</div>
            </div>
            <div className={styles.tablebody}>
              {value?.attach?.map((item, index) => (
                <div className={styles.tr} key={item.uid}>
                  <div className={classNames(styles.td, styles.name)}>
                    <i className={classNames(styles.icon)} />
                    <div className={styles.text}>{item.name}</div>
                  </div>
                  <div className={classNames(styles.td, styles.type)}>压缩包</div>
                  <div className={classNames(styles.td, styles.size)}>
                    {formatSizeUnits(item.size)}
                  </div>
                  <div className={classNames(styles.td, styles.action)}>
                    {item.status === 'uploading' && (
                      <div className={styles.percent}>{item.percent > 99 ? 99 : item.percent}%</div>
                    )}
                    {item.status === 'error' && <div className={styles.error}>上传失败</div>}
                    {item.status !== 'uploading' && (
                      <div
                        className={classNames(styles.button, styles.delete)}
                        onClick={() => handleDeleteAttach(index, item)}
                      >
                        删除
                      </div>
                    )}
                  </div>
                </div>
              ))}
              {value?.disk?.map((item, index) => (
                <div className={styles.tr} key={item.aid}>
                  <div className={classNames(styles.td, styles.name)}>
                    <i className={classNames(styles.icon, styles.disk)} />
                    <div className={styles.text}>{item.name}</div>
                  </div>
                  <div className={classNames(styles.td, styles.type)}>网盘地址</div>
                  <div className={classNames(styles.td, styles.size)}>-</div>
                  <div className={classNames(styles.td, styles.action)}>
                    <div className={classNames(styles.button)} onClick={() => handleEditDisk(item)}>
                      编辑
                    </div>
                    <div
                      className={classNames(styles.button, styles.delete)}
                      onClick={() => handleDeleteDisk(index, item)}
                    >
                      删除
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
      {diskShow && (
        <DiskModal
          onClose={() => {
            setDiskShow(false);
            setDiskInitialValues({});
          }}
          onSave={handleDiskSave}
          initialValues={diskInitialValues}
        />
      )}
    </div>
    // <div
    //   className={classNames(
    //     styles.uploadprocess,
    //     className,
    //     `uploadprocess-process-${info.status}`,
    //   )}
    //   style={style}
    // >
    //   <InnerUpload ref={UploadRef} {...(upLoadProps as any)} className={styles.upload}>
    //     <div className={classNames(styles.process, 'uploadprocess-process', styles[info.status])}>
    //       <i
    //         className={classNames(styles.processInner, 'uploadprocess-process-inner')}
    //         style={{ width: info.status === 'done' ? '100%' : `${info.percent || 0}%` }}
    //       />
    //       <div className={classNames(styles.textWrapper, 'uploadprocess-process-text')}>
    //         {prefix}
    //         <span className={styles.text}>{info.text}</span>
    //       </div>

    //       <div className={classNames(styles.percent, 'uploadprocess-process-percent')}>
    //         <i className={classNames(styles['icon-success'], 'uploadprocess-process-icon')} />
    //         <i className={styles['icon-delete']} onClick={handleRemoveFile} />
    //         {info.status === 'uploading' && `${info.percent || 0}%`}
    //       </div>
    //     </div>
    //   </InnerUpload>
    // </div>
  );
};

export default MaterialUpload;
